# Python生成器（send、close、throw）方法详解
## Python生成器send()方法
def intNum():
    print("开始执行")
    for i in range(5):
        yield i
        print("继续执行")

num = intNum()
print(num.send(None))
print(num.send(None))
print()

def foo():
    bar_a = yield "hello"
    bar_b = yield bar_a
    yield bar_b

f = foo()
print(f.send(None))
print(f.send("C语言中文网"))
print(f.send("http://c.biancheng.net"))
print()

## Python生成器close()方法
def foo():
    try:
        yield 1
    except GeneratorExit:
        print("捕获到 GeneratorExit")

f = foo()
print(next(f))
f.close()
print()

def foo():
    try:
        yield 1
    except GeneratorExit:
        print("捕获到 GeneratorExit")
        #yield 2 # 抛出 RuntimeError: generator ignored GeneratorExit 异常

f = foo()
print(next(f))
f.close()
print()

def foo():
    yield "c.biancheng.net"
    print("生成器停止执行")

f = foo()
print(next(f))
f.close()
#next(f) # 原本应输出”生成器停止执行“，实际出现 StopIteration 异常
print()

## Python生成器throw()方法
def foo():
    try:
        yield 1
    except ValueError:
        print("捕获到 ValueError")

f = foo()
print(next(f))
f.throw(ValueError) # 抛出 StopIteration 异常
